﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using Entidades.Configuracion;

namespace DAL
{
    public static class Funciones
    {
        private const string path = "config.xml";
        private static string source = String.Empty;
        private static string catalog = String.Empty;
        public static bool actualizados = false;

        public static string connectionString = String.Empty;

        public static void DataAccessConnection()
        {
            if (Funciones.actualizados)
            {
                connectionString = SetConnectionString();
            }
            else
            {
                ReadConfigFile();
            }
        }

        /// <summary>
        /// Loads the database source & catalog from a xml file.
        /// </summary>
        private static void ReadConfigFile()
        {
            ConfiguracionXML config = new ConfiguracionXML();

            if (File.Exists(path))
            {
                XmlOperations xml = new XmlOperations();

                config = xml.deserialize(path);
                Funciones.source = config.BaseXml.Source;
                Funciones.catalog = config.BaseXml.Catalog;
            }

            if (String.IsNullOrEmpty(source))
            {
                throw new Exception("Must provide the SQL Server name instance.");
            }
            else
            {
                connectionString = SetConnectionString();
                actualizados = true;
            }
        }

        /// <summary>
        /// Set up the chain of connection depending on whether the sample database is attached or not.
        /// </summary>
        /// <returns>Connection string</returns>
        private static string SetConnectionString()
        {
            return "Data Source=" + source + "; Initial Catalog=" + catalog + "; Integrated Security=SSPI; Min Pool Size=5;Max Pool Size=100;";
        }
    }
}
